package com.jd.jim.gateway.service;

import com.jd.jim.gateway.kit.NetAddressIsReachable;
import com.jd.jim.common.enums.StatusEnum;
import com.jd.jim.common.exception.JIMException;
import com.jd.jim.common.pojo.RouteInfo;
import com.jd.jim.gateway.cache.ServerCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author ：sizegang
 * @description： 公共服务 service
 * @version:  1.0
 */
@Component
public class CommonBizService {
    private static Logger logger = LoggerFactory.getLogger(CommonBizService.class);


    @Autowired
    private ServerCache serverCache;

    /**
     * check ip and port
     * 检测服务是否可用
     * @param routeInfo
     */
    public void checkServerAvailable(RouteInfo routeInfo) {
        boolean reachable = NetAddressIsReachable.checkAddressReachable(routeInfo.getIp(), routeInfo.getTimServerPort(), 1000);
        if (!reachable) {

            logger.error("ip={}, port={} are not available", routeInfo.getIp(), routeInfo.getTimServerPort());

            // rebuild cache
            serverCache.rebuildCacheList();
            // 抛出不可用异常
            throw new JIMException(StatusEnum.SERVER_NOT_AVAILABLE);
        }

    }
}
